from django.http import HttpResponse

import cStringIO as StringIO
import re

import ho.pisa as pisa

from django.conf import settings

import logging
class PisaNullHandler(logging.Handler):
  def emit(self, record):
    pass
logging.getLogger("ho.pisa").addHandler(PisaNullHandler())

class PrintingMiddleware:
  css_remover = re.compile(r'\<link.+?jquery-ui-1.8.11.custom.css.+?>')
  css_remover2 = re.compile(r'\<link.+?jquery\.drag_drop_multi_select_alpha\.css.+?>')
  title = re.compile(r'.*\<h1\>\<.+?\>(.+?)\<.+?\>\<\/h1\>.*')
  
  def process_request(self, request):
    if request.path_info[:6] == '/print':
      request.printing = True
      request.path_info = request.path_info[6:]
      request.path = request.path.replace('/print', '')
      if request.path_info[:4] == '/pdf':
        request.pdf = True
        request.path_info = request.path_info[4:]
        request.path = request.path.replace('/pdf', '')
      else:
        request.pdf = False
    else:
      request.printing = False
    
    return None
  
  def process_response(self, request, response):
    if request.printing is True:
      content = response.content.replace('theme.css', 'theme_print.css')
      # Add font embedd
      font_embedd = """
        <script> window.print(); </script>
        <style>
          @font-face {
            font-family: NormalFont; 
            src: url(/media/fonts/arial.ttf);
          }
        </style>
      """
      content = content.replace('</head>', '{0}</head>'.format(font_embedd))
      
      if request.pdf is True:
        # Absolutize media files
        content = content.replace('/media/', '{0}/'.format(settings.MEDIA_ROOT))
        content = self.css_remover.sub('', content)
        content = self.css_remover2.sub('', content)
        
        title = self.title.search(content).group(1).replace(' ', '_')
        
        # Make the PDF
        pdf_buffer = StringIO.StringIO()
        pisa.CreatePDF(content, pdf_buffer)
        output_response = HttpResponse(pdf_buffer.getvalue(), mimetype = 'application/pdf')
        del pdf_buffer
        output_response['Content-Disposition'] = 'attachment; filename="{0}.pdf";'.format(title)
      else:
        output_response = HttpResponse(content)
    else:
      output_response = response
    
    return output_response